/*
 * Copyright (C) 2015-2016  Nicola Spanti (RyDroid) <dev@nicola-spanti.info>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */


/**
 * @file
 * @brief Functions to detect collisions of 2D elements
 */


#ifndef PLANET_WARS_2D_RT_CORE_COLLISION_2D_GENERIC_H
#define PLANET_WARS_2D_RT_CORE_COLLISION_2D_GENERIC_H


/* For explanations about collision algorithms, you can see:
   http://devmag.org.za/2009/04/13/basic-collision-detection-in-2d-part-1/
*/


#define COLLISION_2D_LINE_LINE_STRUCT(line1_start,			\
				      line2_start,			\
				      line1_end,			\
				      line2_end)			\
  (									\
   ((line1_end->y - line1_start->y) * (line2_end->y - line2_start->y)	\
    -									\
    (line1_end->x - line1_start->x) * (line2_end->x - line2_start->x)	\
    ) != 0								\
									)

#define COLLISION_2D_RECTANGLE_RECTANGLE_NO_STRUCT(pos1_x,		\
						   pos1_y,		\
						   pos2_x,		\
						   pos2_y,		\
						   size1_x,		\
						   size1_y,		\
						   size2_x,		\
						   size2_y)		\
  !(									\
    pos1_y + size1_y < pos2_y /* outside bottom */ ||			\
    pos1_y > pos2_y + size2_y /* outside top    */ ||			\
    pos1_x > pos2_x + size2_x /* outside left   */ ||			\
    pos1_x + size1_x < pos2_x /* outside right  */			\
									)

#define COLLISION_2D_RECTANGLE_RECTANGLE_STRUCT(pos1,			\
						pos2,			\
						size1,			\
						size2)			\
  COLLISION_2D_RECTANGLE_RECTANGLE_NO_STRUCT(pos1->x,  pos1->y,		\
					     pos2->x,  pos2->y,		\
					     size1->x, size1->y,	\
					     size2->x, size2->y		\
					     )

#define IS_SIZE_IN_SIZE_2D_STRUCT(size1, size2)		\
  (size1->x >= size2->x && size1->y >= size2->y)

#define IS_RECTANGLE_IN_SIZE_2D_STRUCT(size1,	\
				       pos2,	\
				       size2)	\
  (size1->x >= pos2->x + size2->x &&		\
   size1->y >= pos2->y + size2->y)

#define IS_RECTANGLE_IN_RECTANGLE_2D_STRUCT(pos1,			\
					    pos2,			\
					    size1,			\
					    size2)			\
  (									\
   pos1->x <= pos2->x &&						\
   pos1->y <= pos2->y &&						\
   pos1->x + size1->x >= pos2->x + size2->x &&				\
   pos1->y + size1->y >= pos2->y + size2->y				\
									)


#endif
